package com.lksy.core.config;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author jzx
 * @date 2016-08-01 16:19:12 星期一
 */
public class EncryptPropertyPlaceholderConfigurer
		extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer {

	private String[] encryptPropNames = { "db.username", "db.password" };

	@Override
	protected String convertProperty(String propertyName, String propertyValue) {
		if (isEncryptProp(propertyName)) {
			String decryptValue = convUTF8(Base64.decryptBASE64(propertyValue), "utf-8");
			return decryptValue;
		} else {
			return propertyValue;
		}
	}

	private boolean isEncryptProp(String propertyName) {
		for (String encryptPropName : encryptPropNames) {
			if (encryptPropName.equals(propertyName)) {
				return true;
			}
		}
		return false;
	}

	public static String convUTF8(byte bytes[], String charsetName) {
		try {
			return new String(bytes, charsetName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	static class Base64 {
		public static byte[] decryptBASE64(String key) {
			try {
				return (new BASE64Decoder()).decodeBuffer(key);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		public static String encryptBASE64(byte[] key) {
			return (new BASE64Encoder()).encodeBuffer(key);
		}
	}
}
